import * as UserDao from '../../dao/UserDao'
import { NavigationActions, createAction, AsyncStorage } from '../../utils';

export default {
  namespace: 'user',
  state: {
    userInfo: {},
    loginError: false,
    loginErrorMsg: '',
    registerError: false,
    registerErrorMsg: '',
    updateError: false,
    updateErrorMsg: '',
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
  },
  effects: {
    *login({ payload }, { call, put }) {
      console.log('payload :', payload);
      const data = yield call(UserDao.login, payload);
      if (data.status) {
        yield put(createAction('updateState')({
          userInfo: data.msg
        }))
        AsyncStorage.set('userInfo', data.msg);
        if (data.msg.ustatus == 'NEW') {
          yield put(NavigationActions.navigate({ routeName: 'CompleteInfo' }))
        } else {
          yield put(NavigationActions.navigate({ routeName: 'Main' }))
        }
      } else {
        yield put(createAction('updateState')({
          loginError: true,
          loginErrorMsg: data.msg
        }))
      }
      console.log(data);
    },
    *register({ payload }, { call, put }) {
      console.log('payload :', payload);
      const data = yield call(UserDao.register, payload);
      if (data.status) {
        yield put(NavigationActions.navigate({ routeName: 'CompleteInfo' }))
      } else {
        yield put(createAction('updateState')({
          registerError: true,
          registerErrorMsg: data.msg
        }))
      }
      console.log(data);
    },
    *update({ payload }, { call, put, select }) {
      const uid = yield select(state => state.user.userInfo.uid);
      let params = {
        uid: uid,
        ...payload
      }
      const data = yield call(UserDao.update, params)
      console.log(data);
      if (data.status) {
        yield put(NavigationActions.navigate({ routeName: 'Main' }))
      } else {
        yield put(createAction('updateState')({
          updateError: true
        }))
      }
    },
    *updateImage({ payload }, { call, put, select }) {
      const uid = yield select(state => state.user.userInfo.uid);
      let params = {
        //uid: uid,
        ...payload
      }
      console.log(params);
      let formData = new FormData()
      for (var key in params) {
        formData.append(key, params[key]);
      }
      console.log(formData);
      const data = yield call(UserDao.updateImage, params)
      console.log(data);
    }
  },
}